package com.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceiveThread implements Runnable{

    private DatagramSocket socket = null;
    private int port;

    /**
     *
     * @param port : 本地接收端口
     */
    public TalkReceiveThread(int port) {
        this.port = port;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                //创建一个包裹来接收数据
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);
                //拆开包裹
                String receiveData = new String(packet.getData(),0,packet.getLength());
                if (receiveData.contains(":")){
                    System.out.println();
                    System.out.println(receiveData);
                }
                if (receiveData.trim().contains("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }

}
